#include "head.h"

/*******************输入密码**************************/
// void input_password(char* str)
// {
// 	char c;
// 	int i = 0;
// 	while (1) {
// 		c = getchar();
// 		if (c == '\r') {
// 			str[i] = '\0';
// 			printf("\n");
// 			break;
// 		}
// 		if (c == '\b') {
// 			printf("\b \b");
// 			i--;
// 			continue;
// 		}
// 		str[i++] = c;
// 		printf("*");
// 	}
// }

int repeatCheckU(puser puhead, char* uname)
{
	puser pcur = puhead;
	while (pcur)
	{
		if (!strcmp(pcur->uname,uname))
		{
			return 1;
		}
		pcur = pcur->pnext;
	}
	return -1;
}

int userInsert(puser* ppuhead, puser* pputail, char* uname, char* pass, int right)
{
	int ret = -1;//查找的返回值，用于判断是否有相同用户信息
	ret = repeatCheckU(*ppuhead, uname);
	if (1 == ret)
	{
		printf("用户名不可以重复！\n");
		return -1;
	}
	if (right != 1 && right != 2)
	{
		printf("用户权限输入错误，超级管理员请输入1，其他输2！\n");
		system("pause");
		return -1;
	}
	puser pcur = (puser)malloc(sizeof(user));
	memset(pcur, 0, sizeof(user));
	strcpy(pcur->uname, uname);
	strcpy(pcur->pass, pass);
	pcur->right = right;
	if (NULL==*ppuhead)//if (ppuhead = NULL)！！！
	{
		*ppuhead = *pputail = pcur;
	}
	else
	{
		(*pputail)->pnext = pcur;
		*pputail = pcur;
	}
	return 1;
}
void printUser(puser puhead)
{
	puser pcur = puhead;
	while (pcur)
	{
		if (1 == pcur->right)
		{
			printf("超级管理员：%s\n", pcur->uname);
		}
		else if (2 == pcur->right)
		{
			printf("用户名：%s\n", pcur->uname);
		}
		pcur = pcur->pnext;
	}
}
int login(puser puhead,char* uname, char* pass)
{
	int flag1 = 1;//用于标记用户名是否匹配
	int flag2 = 1;//用于标记密码是否匹配
	puser pcur = puhead;
	while (pcur != NULL&&flag1!=0)
	{
		flag1 = strcmp(uname, pcur->uname);
		if (0 == flag1)
		{
			flag2 = strcmp(pass, pcur->pass);
			if (0 == flag2)
			{
				printf("登陆成功！\n");
				return pcur->right;
				system("pause");
			}
			else
			{
				printf("密码输入错误！\n");
				return -1;
			}
		}
		else
		{
			pcur = pcur->pnext;
		}
	}
	if (!pcur)
	{
		printf("没有该用户名！\n");
		return -1;
	}
	return 0;
}
void deleteUser(puser* pphead, puser* pptail, char *str)
{
	puser pcur = *pphead;
	puser ppre = *pphead;
	if (*pphead == *pptail)
	{
		free(pcur);
		*pphead = *pptail = NULL;
	}
	else
	{
		if (!strcmp((*pphead)->uname,str))//删除对象为头指针
		{
			(*pphead) = (*pphead)->pnext;
			free(pcur);
		}
		else if (!strcmp((*pptail)->uname, str))//删除对象为尾指针
		{
			ppre = *pphead;
			pcur = (*pphead)->pnext;
			while ((*pptail) != pcur)
			{
				ppre = ppre->pnext;
				pcur = pcur->pnext;
			}
			(*pptail) = ppre;
			ppre->pnext = NULL;
			free(pcur);
		}
		else//其他情况
		{
			pcur = pcur->pnext;
			while (strcmp(pcur->uname,str))
			{
				ppre = ppre->pnext;
				pcur = pcur->pnext;
			}
			ppre->pnext = pcur->pnext;
			free(pcur);
		}
	}
}
